import { MissTargetError } from './../filter/error.filter';
import {
  Transport,
  TransportQueryCondition,
} from './../entity/transport.entity';
import {
  Body,
  Controller,
  Del,
  Get,
  Inject,
  Param,
  Post,
  Put,
} from '@midwayjs/core';
import { BillCodeGenerator } from '../service/tool.service';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';

@Controller('/transport')
export class TransportController {
  @Inject()
  billCodeGenerator: BillCodeGenerator;
  @InjectEntityModel(Transport)
  repo: Repository<Transport>;
  @Post('/insert')
  async insert(@Body() transport: Transport): Promise<Transport> {
    transport.transportId = await this.billCodeGenerator.nextCode('TR');
    console.log(transport);
    return await this.repo.save(transport);
  }
  /*
  SELECT * from Transport t
  WHERE t.supplier like '%金太阳%' and t.transportTime <= '2023-05-04' and t.transportTime >= '2023-04-04'
  ORDER BY t.transportTime DESC
  LIMIT 0,2
  */
  @Post('/query')
  async query(@Body() qc: TransportQueryCondition) {
    const {
      supplierLike,
      transportTimeStart,
      transportTimeEnd,
      pageNum,
      pageSize,
    } = qc;
    const pageStart = (pageNum - 1) * pageSize;
    const builder = this.repo.createQueryBuilder('t');
    if (supplierLike) {
      builder.andWhere('t.supplier like :s', { s: '%' + supplierLike + '%' });
    }
    if (transportTimeEnd) {
      builder.andWhere('t.transportTime <= :end', { end: transportTimeEnd });
    }
    if (transportTimeStart) {
      builder.andWhere('t.transportTime >= :transportTimeStart', {
        transportTimeStart,
      });
    }
    builder.orderBy('t.transportTime', 'DESC');
    builder.offset(pageStart).limit(pageSize);
    const r = await builder.printSql().getManyAndCount();
    console.log(r);
    return {
      total: r[1],
      results: r[0],
    };
  }
  @Get('/find/:id')
  async findById(@Param('id') id: string) {
    const tr = await this.repo.findOneBy({ transportId: id });
    if (!tr) {
      throw new MissTargetError('id :' + id + ' 的数据不存在');
    }
    return tr;
  }
  @Del('/remove/:id')
  async removeById(@Param('id') id: string) {
    const tr = await this.repo.findOneBy({ transportId: id });
    if (!tr) {
      throw new MissTargetError('id :' + id + ' 待删除的数据不存在');
    }
    const r = await this.repo.remove(tr);
    return r;
  }
  @Put('/modify')
  async modify(@Body() transport: Transport) {
    const trFromDB = await this.repo.findOneBy({
      transportId: transport.transportId,
    });
    if (!trFromDB) {
      throw new MissTargetError(
        'id :' + transport.transportId + ' 待修改的数据不存在'
      );
    }
    return await this.repo.save(transport);
  }
}
